import { useEffect, useState } from "react";

export default function StudyUseEffect() {
	// 默认message是空
	const [message, setMessage] = useState<string>("");

	const changeMessage = (value: string) => {
		setMessage(value);
	};

	useEffect(() => {
		console.log("页面初始化时，调用changeMessage");
		changeMessage(" this is  useEffect change");
	}, []);

	const [count, setCount] = useState(0);
	const [text, setText] = useState("Hello");

	useEffect(() => {
		console.log("Effect ran due to count or text change");
		// 可以在此处处理 count 和 text 变化时的副作用
	}, [count, text]); // 依赖 count 和 text，当其中任意一个发生变化时，useEffect 会重新执行

	return (
		<div>
			<h2> 2. Study useEffect</h2>
			<div>message:{message}</div>
			<button onClick={() => changeMessage("this is BtnChange")}>change Message</button>
			<div>
				<p>Count: {count}</p>
				<button onClick={() => setCount(count + 1)}>Increase Count</button>
				<p>Text: {text}</p>
				<button onClick={() =>setText(text === "Hello" ? "World" : "Hello")}>Toggle Text</button>
			</div>
		</div>
	);
}
